package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.entity.system.SysMenu;
import com.ruoyi.common.entity.system.SysRole;
import com.ruoyi.system.entity.SysRoleMenu;
import com.ruoyi.system.entity.SysUserRole;
import com.ruoyi.system.mapper.SysMenuMapper;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysRoleMenuMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.ISysMenuService;
import javafx.animation.ParallelTransition;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.stream.StreamInfo;
import org.springframework.stereotype.Service;

import javax.annotation.processing.RoundEnvironment;
import java.lang.reflect.ParameterizedType;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 菜单 业务层处理
 * 
 * @author LiuXiaoYu
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;

    @Override
    public Set<String> selectMenuPermsByUserId(Long userId) {
        List<SysUserRole> userRoleEntities = sysUserRoleMapper.selectList(new QueryWrapper<SysUserRole>().eq("user_id", userId));
        List<Long> collect = userRoleEntities.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
        List<SysRole> sysRoles=sysRoleMapper.selectList(new QueryWrapper<SysRole>().eq("status",0).in("role_id",collect));
        List<Long> roleIds=sysRoles.stream().map(SysRole::getRoleId).collect(Collectors.toList());
        List<SysRoleMenu> sysRoleMenuEntities = sysRoleMenuMapper.selectList(new QueryWrapper<SysRoleMenu>().select("distinct menu_id").in("role_id", roleIds));
        List<Long> menuIds = sysRoleMenuEntities.stream().map(SysRoleMenu::getMenuId).collect(Collectors.toList());
        List<SysMenu> menus = sysMenuMapper.selectList(new QueryWrapper<SysMenu>().eq("status",0).in("menu_id",menuIds));
        Set<String> perms = menus.stream().map(SysMenu::getPerms).collect(Collectors.toSet());
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms) {
            if (StringUtils.isNotEmpty(perm)) {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }
}
